package top.hhydra.mimall.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import top.hhydra.mimall.constant.MallConst;
import top.hhydra.mimall.entity.User;
import top.hhydra.mimall.form.UserLoginForm;
import top.hhydra.mimall.form.UserRegisterForm;
import top.hhydra.mimall.service.IUserService;
import top.hhydra.mimall.vo.ResponseVo;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author SaiyaEmon
 * @since 2020-02-08
 */
@RestController
@Slf4j
@Api(value="用户controller",tags={"用户操作接口"})
public class UserController {

    @Autowired
    IUserService userService;

    @PostMapping("/user/register")
    @ApiOperation(value = "注册", notes = "账号密码邮箱必输")
    public ResponseVo<User> register(@Valid @RequestBody UserRegisterForm userForm) {
        log.info("/user/login");

        User user = new User();
        BeanUtils.copyProperties(userForm, user);
        return userService.register(user);
    }

    @PostMapping("/user/login")
    @ApiOperation(value = "登录", notes = "账号密码必输")
    public ResponseVo<User> login(@Valid @RequestBody UserLoginForm userForm,
                                  HttpSession session){
        log.info("/user/login sessionId={}", session.getId());

        User user = new User();
        BeanUtils.copyProperties(userForm, user);
        ResponseVo<User> loginResponseVo = userService.login(user);
        session.setAttribute(MallConst.CURRENT_USER,loginResponseVo.getData());

        return loginResponseVo;
    }

    @GetMapping("/user")
    @ApiOperation(value = "获取登录用户信息")
    public ResponseVo<User> userInfo(HttpSession session){
        log.info("/user sessionId={}", session.getId());
        User currentUser = (User) session.getAttribute(MallConst.CURRENT_USER);
        return ResponseVo.success(currentUser);
    }

    @PostMapping("/user/logout")
    @ApiOperation(value = "退出登录")
    public ResponseVo<User> logout(HttpSession session) {
        log.info("/user/logout sessionId={}", session.getId());
        session.removeAttribute(MallConst.CURRENT_USER);
        return ResponseVo.success();
    }

}
